﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using LCL.Caching;
namespace LCL.Caching.Provider
{
    /// <summary>
    /// System.Web.Caching
    /// </summary>
    public class WebCacheProvider : ICacheProvider
    {
        protected static volatile System.Web.Caching.Cache _cache = System.Web.HttpRuntime.Cache;
        public T Get<T>(string key)
        {
            if (key == null || key.Length == 0)
            {
                return default(T);
            }
            return (T)_cache[key];
        }
        public void Set(string key, object data, int cacheTime)
        {
            if (key == null || key.Length == 0 || data == null)
            {
                return;
            }
            //表示永不过期
            if (cacheTime == 0)
            {
                _cache.Insert(key, data, null, DateTime.MaxValue, TimeSpan.Zero, System.Web.Caching.CacheItemPriority.High, null);
            }
            else
            {
                _cache.Insert(key, data, null, DateTime.Now.AddSeconds(cacheTime), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.High, null);
            }
        }
        public bool Exists(string key)
        {
            if (key == null || key.Length == 0)
            {
                return false;
            }
            return _cache[key] != null;
        }
        public void Remove(string key)
        {
            if (key == null || key.Length == 0)
            {
                return;
            }
            _cache.Remove(key);
        }
        public void RemoveByPattern(string pattern)
        {
            var regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase);
            var keysToRemove = new List<String>();
            IDictionaryEnumerator CacheEnum = HttpRuntime.Cache.GetEnumerator();
            while (CacheEnum.MoveNext())
            {
                if (regex.IsMatch(CacheEnum.Key.ToString()))
                    keysToRemove.Add(CacheEnum.Key.ToString());
            }
            foreach (string key in keysToRemove)
            {
                Remove(key);
            }
        }
        public void Clear()
        {
            IDictionaryEnumerator CacheEnum = HttpRuntime.Cache.GetEnumerator();
            while (CacheEnum.MoveNext())
            {
                _cache.Remove(CacheEnum.Key.ToString());
            }
        }
    }
}
